package com.jt.blog.controller.AdminManage;

import com.jt.blog.service.SetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author : 戴瑞
 * @Description :系统设置相关功能
 * @create : 2018-03-27 21:40
 **/

@RequestMapping("/back/admin")
@Controller
public class SystemController {

    @RequestMapping("/backup")
    public String backupShow() {
        return "back/system/backup";
    }

    @Autowired
    private SetingService setingService;

    @Value("${sql-backup}")
    private String parentFilePath;

    /**
     * 手动执行数据备份
     *
     * @return
     */
    @RequestMapping("/execute/backup")
    @ResponseBody
    public Object backupDatabase() {
        return setingService.executeBackup();
    }

    @RequestMapping("/backup/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
        ResponseEntity<byte[]> entity = null;

        File file = new File(parentFilePath + File.separator + "backup.sql");
        if (file.exists()) {
            byte[] body = null;
            InputStream is = null;
            is = new FileInputStream(file);
            body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchement;filename=" + file.getName());
            HttpStatus statusCode = HttpStatus.OK;
            entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        } else {
            // 文件不存在
            entity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return entity;
    }

}
